<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author lzw
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'operating:ftdsDebtorManagement:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="100%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="m-1 pr-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm">
      <template #ftdsOrderList>
        <BasicTable
          @register="registerFtdsOrderTable"
          @row-click="handleFtdsOrderRowClick"
        />
        <a-button class="mt-2" @click="handleFtdsOrderAdd" v-auth="'operating:ftdsDebtorManagement:edit'">
          <Icon icon="i-ant-design:plus-circle-outlined" /> {{ t('新增') }}
        </a-button>
      </template>
    </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts" setup name="ViewsOperatingFtdsDebtorManagementForm">
  import { ref, unref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicTable, useTable } from '/@/components/Table';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { FtdsDebtorManagement, ftdsDebtorManagementSave, ftdsDebtorManagementForm } from '/@/api/operating/ftdsDebtorManagement';

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('operating.ftdsDebtorManagement');
  const { showMessage } = useMessage();
  const { meta } = unref(router.currentRoute);
  const record = ref<FtdsDebtorManagement>({} as FtdsDebtorManagement);

  const getTitle = computed(() => ({
    icon: meta.icon || 'i-ant-design:book-outlined',
    value: record.value.isNewRecord ? t('新增债务人管理') : t('编辑债务人管理'),
  }));

  const inputFormSchemas: FormSchema[] = [
    {
      label: t('所属甲方'),
      field: 'managementSsjf',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
    },
    {
      label: t('平台方'),
      field: 'managementPtf',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
    },
    {
      label: t('处置方'),
      field: 'managementCzf',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
    },
    {
      label: t('处置方式'),
      field: 'managementCzfs',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
    },
    {
      label: t('委案日期'),
      field: 'managementWarq',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
    },
    {
      label: t('债务人姓名'),
      field: 'managementZwrxm',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
    },
    {
      label: t('身份证号码'),
      field: 'managementSfzhm',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
    },
    {
      label: t('出生日期'),
      field: 'managementCsrq',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
    },
    {
      label: t('手机号码'),
      field: 'managementSjhm',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
    },
    {
      label: t('身份证地址'),
      field: 'managementSfzdz',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
    },
    {
      label: t('民族'),
      field: 'managementMz',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
    },
    {
      label: t('性别'),
      field: 'managementXb',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
    },
    {
      label: t('法院'),
      field: 'managementFy',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
    },
    {
      label: t('共债数量'),
      field: 'managementGzsl',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
    },
    {
      label: t('总逾期本金'),
      field: 'managementZyqbj',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
    },
    {
      label: t('总逾期利息'),
      field: 'managementZyqlx',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
    },
    {
      label: t('总逾期罚息'),
      field: 'managementZyqfx',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
    },
    {
      label: t('负责人'),
      field: 'managementFzr',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
    },
    {
      label: t('还款状态'),
      field: 'managementHkzt',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
    },
    {
      label: t('订单管理'),
      field: 'ftdsOrderList',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'ftdsOrderList',
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { lg: 6, md: 24 },
  });

  const [registerFtdsOrderTable, ftdsOrderTable] = useTable({
    actionColumn: {
      width: 60,
      actions: (record: Recordable) => [
        {
          icon: 'i-ant-design:delete-outlined',
          color: 'error',
          popConfirm: {
            title: '是否确认删除',
            confirm: handleFtdsOrderDelete.bind(this, record),
          },
          auth: 'operating:ftdsDebtorManagement:edit',
        },
      ],
    },
    rowKey: 'id',
    pagination: false,
    bordered: true,
    size: 'small',
    inset: true,
  });

  async function setFtdsOrderTableData(_res: Recordable) {
    ftdsOrderTable.setColumns([
      {
        title: t('订单号'),
        dataIndex: 'orderDdh',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 100,
        },
        editRule: false,
      },
      {
        title: t('放款主体'),
        dataIndex: 'orderFkzt',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 100,
        },
        editRule: false,
      },
      {
        title: t('放款金额'),
        dataIndex: 'orderFkje',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 100,
        },
        editRule: false,
      },
      {
        title: t('放款日期'),
        dataIndex: 'orderFkrq',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 100,
        },
        editRule: false,
      },
      {
        title: t('剩余本金'),
        dataIndex: 'orderSybj',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 100,
        },
        editRule: false,
      },
      {
        title: t('剩余利息'),
        dataIndex: 'orderSylx',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 100,
        },
        editRule: false,
      },
      {
        title: t('剩余罚息'),
        dataIndex: 'orderSyfx',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 100,
        },
        editRule: false,
      },
      {
        title: t('借款期数'),
        dataIndex: 'orderJkqs',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 100,
        },
        editRule: false,
      },
      {
        title: t('逾期日期'),
        dataIndex: 'orderYqrq',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 100,
        },
        editRule: false,
      },
      {
        title: t('案件进展'),
        dataIndex: 'orderAjjz',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 100,
        },
        editRule: false,
      },
      {
        title: t('立案状态'),
        dataIndex: 'orderLazt',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 100,
        },
        editRule: false,
      },
      {
        title: t('审核意见'),
        dataIndex: 'orderShyj',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 100,
        },
        editRule: false,
      },
      {
        title: t('APP'),
        dataIndex: 'orderApp',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 100,
        },
        editRule: false,
      },
      {
        title: t('担保方名称'),
        dataIndex: 'orderDbfmc',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 100,
        },
        editRule: false,
      },
      {
        title: t('代偿金额'),
        dataIndex: 'orderDcje',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 100,
        },
        editRule: false,
      },
      {
        title: t('代偿日期'),
        dataIndex: 'orderDcrq',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 100,
        },
        editRule: false,
      },
      {
        title: t('备注'),
        dataIndex: 'orderBz',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editRule: false,
      },
    ]);
    ftdsOrderTable.setTableData(record.value.ftdsOrderList || []);
  }

  function handleFtdsOrderRowClick(record: Recordable) {
    record.onEdit?.(true, false);
  }

  function handleFtdsOrderAdd() {
    ftdsOrderTable.insertTableDataRecord({
      id: new Date().getTime(),
      isNewRecord: true,
      editable: true,
    });
  }

  function handleFtdsOrderDelete(record: Recordable) {
    ftdsOrderTable.deleteTableDataRecord(record);
  }

  async function getFtdsOrderList() {
    let ftdsOrderListValid = true;
    let ftdsOrderList: Recordable[] = [];
    for (const record of ftdsOrderTable.getDataSource()) {
      if (!(await record.onEdit?.(false, true))) {
        ftdsOrderListValid = false;
      }
      ftdsOrderList.push({
        ...record,
        id: !!record.isNewRecord ? '' : record.id,
      });
    }
    for (const record of ftdsOrderTable.getDelDataSource()) {
      if (!!record.isNewRecord) continue;
      ftdsOrderList.push({
        ...record,
        status: '1',
      });
    }
    if (!ftdsOrderListValid) {
      throw { errorFields: [{ name: ['ftdsOrderList'] }] };
    }
    return ftdsOrderList;
  }

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    const res = await ftdsDebtorManagementForm(data);
    record.value = (res.ftdsDebtorManagement || {}) as FtdsDebtorManagement;
    record.value.__t = new Date().getTime();
    setFieldsValue(record.value);
    setFtdsOrderTableData(res);
    setDrawerProps({ loading: false });
  });

  async function handleSubmit() {
    try {
      const data = await validate();
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        id: record.value.id,
      };
      data.ftdsOrderList = await getFtdsOrderList();
      // console.log('submit', params, data, record);
      const res = await ftdsDebtorManagementSave(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('common.validateError'));
      }
      console.log('error', error);
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>
